import { USER_INFO, TOKEN, RECORDS } from '@/constants/common';
import { useService } from '@/utils/services';
import storage from '@/utils/storage';
import config from '@/config';
import { filterTreeData } from '@/model/hos';

const state = {
  token: storage.get(TOKEN) || '',
  userInfo: storage.get(USER_INFO) || {}, // 用户信息
  deptId: 0, // 科室id
  settings: {
    isDisableBed: false // 床位是否已满
  },
  // 当前所在科室
  currentDeptInfo: {},
  // 所有的科室列表
  deptList: [],

  areaList: [],

  dict: {},

  msgNum: 0,
  // 浏览记录
  records: storage.get(RECORDS) || []
};

const getters = {
  isDisableBed: (state) => state.settings.isDisableBed
};

const mutations = {
  // 设置token
  setToken(state, token) {
    state.token = token;
  },

  setIsDisableBed(state, bool) {
    state.settings.isDisableBed = bool;
  },

  setUserInfo(state, info) {
    state.userInfo = info;
  },

  setCurrentDeptInfo(state, info) {
    state.currentDeptInfo = info;
  },

  setDeptList(state, info) {
    state.deptList = info;
  },

  setAreaList(state, list) {
    state.areaList = list;
  },

  setDictData(state, data) {
    state.dict = data;
  },

  setMsgNum(state, num) {
    state.msgNum = num;
  },

  setRecords(state, id) {
    try {
      if (!state.records.includes(id)) {
        state.records.push(id);
        storage.set(RECORDS, state.records);
      }
    } catch {
      console.log('存储失败');
    }
  }
};

const actions = {
  // 获取行政区域
  getAreaList({ commit }) {
    fetch(config.areaJsonURL)
      .then((res) => {
        return res.json();
      })
      .then((res) => {
        commit('setAreaList', filterTreeData(res.areaData));
      });
  },

  getDictResult({ commit }, params) {
    const actions = useService();
    actions.hos.getDictResult({ types: params }).then((res) => {
      let result = res.reduce((cu, item) => {
        cu[item.typeValue] = item.items;
        return cu;
      }, {});
      commit('setDictData', result);
    });
  },

  getSurplus({ commit }) {
    const actions = useService();
    actions.hos.surplus().then((res) => {
      commit('setMsgNum', res?.instantMsg?.num || 0);
    });
  }
};

export default {
  state,
  getters,
  mutations,
  actions
};
